<script setup lang="ts">
import type { orderInfo } from '@/types/order'
import { ref } from 'vue'
import AddressItem from './AddressItem.vue'
import AddressForm from './AddressForm.vue'
import { showFailToast } from 'vant'

const props = defineProps<{
  address: orderInfo[]
}>()

const showAddressForm = ref(false)
const title = ref('')
const addrInit = ref<orderInfo>({
  addressDetail: '',
  id: '',
  receiver: '',
  isDefault: 0,
  mobile: '',
  province: '',
  city: '',
  county: ''
})
const addr = ref<orderInfo>({ ...addrInit.value })
const delAddress = () => {
  // console.log('删除地址')
}
const showPop = (info?: orderInfo, icon?: string) => {
  if (info?.id) {
    // 这里需要判断是出于何种状态，删除/编辑
    if (icon === 'edit') {
      // 编辑收货地址
      title.value = '编辑收货地址'
      addr.value = info
    } else {
      // 删除当前收货地址
      // 需要判断当前收货地址的数量，如果小于等于1，则提示不能删除
      return props.address.length > 1
        ? delAddress()
        : showFailToast('必须有一个收货地址')
    }
  } else {
    // 添加收货地址
    title.value = '添加收货地址'
    addr.value = { ...addrInit.value }
  }
  showAddressForm.value = true
}
</script>

<template>
  <div class="address-list" v-for="item in address" :key="item.id">
    <address-item :item="item" @editAddress="showPop"></address-item>
    <div class="btn">
      <van-button block type="primary" round @click="showPop"
        >添加收货地址</van-button
      >
    </div>
    <van-popup
      v-if="showAddressForm"
      v-model:show="showAddressForm"
      :style="{ height: '100%', width: '100%', 'max-width': '100%' }"
    >
      <address-form
        v-model:showAddressForm="showAddressForm"
        :title="title"
        :addr="addr"
      ></address-form>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.address-list {
  padding: 10px;
  .btn {
    position: fixed;
    bottom: 15px;
    left: 0px;
    right: 0px;
    box-sizing: border-box;
    padding: 0 15px;
  }
}
</style>
